package com.smedi.ismedi.progress.core.port.adapter.persistence.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.smedi.ismedi.progress.core.application.command.*;
import com.smedi.ismedi.progress.core.domain.aggregatemodel.*;
import com.smedi.ismedi.progress.core.domain.repository.ProgressViewRepository;
import com.smedi.ismedi.progress.core.port.adapter.convert.AdapterConverter;
import com.smedi.ismedi.progress.core.port.adapter.persistence.model.*;
import com.smedi.ismedi.progress.core.port.adapter.persistence.mybatis.mapper.ProgressMapper;
import com.smedi.ismedi.progress.core.port.adapter.persistence.mybatis.mapper.ProjectScheduleDetaillMapper;
import com.smedi.ismedi.progress.core.port.adapter.persistence.mybatis.mapper.VersionDetailMapper;
import com.smedi.ismedi.progress.core.port.adapter.persistence.mybatis.mapper.VersionManageMapper;
import com.smedi.ismedi.progress.core.port.adapter.service.TaskRemoteService;
import lombok.AllArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.*;

import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.TASK_NAME_PROGRESS_CONSTRUCTION_APPROVAL;
import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.TASK_TYPE;


/**
 * 基础信息仓库实现类
 *
 * @author cookie
 * @date 2022/07/14
 */
@Repository
@AllArgsConstructor
public class ProgressViewRepositoryImpl implements ProgressViewRepository {
    private final AdapterConverter adapterConverter;
    private final ProgressMapper progressMapper;
    private final VersionDetailMapper versionDetailMapper;
    private final VersionManageMapper versionManageMapper;
    private final ProjectScheduleDetaillMapper projectScheduleDetaillMapper;
    private final TaskRemoteService taskRemoteService;





    @Override
    public ProgressView scheduleViewAndApproval(ProgressViewCommand progressViewCommand) {
        LambdaQueryWrapper<VersionManageEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(progressViewCommand.getProjectId()), VersionManageEntity::getProjectId, progressViewCommand.getProjectId());
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(progressViewCommand.getId()), VersionManageEntity::getId, progressViewCommand.getId());
        VersionManageEntity progressEntity = versionManageMapper.selectOne(lambdaQueryWrapper);
        ProgressView progressView = adapterConverter.progressEntityToProgressView(progressEntity);
        if (progressEntity != null){
            LambdaQueryWrapper<VersionDetailEntity> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(progressViewCommand.getProjectId()), VersionDetailEntity::getProjectId, progressViewCommand.getProjectId());
            lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(progressViewCommand.getId()), VersionDetailEntity::getVersionManageId, progressViewCommand.getId());
            lambdaQueryWrapper1.like(ObjectUtils.isNotNull(progressViewCommand.getTaskType()), VersionDetailEntity::getType, progressViewCommand.getTaskType());
            List<VersionDetailEntity> versionDetails = versionDetailMapper.selectList(lambdaQueryWrapper1);
            List<VersionDetail> lists = adapterConverter.versionDetailEntityToVersionDetail(versionDetails);

            VersionDetail[] arry = new VersionDetail[lists.size()];
            for(int i = 0;i<lists.size();i++){
                arry[i] = lists.get(i);
            }
            /*Arrays.sort(arry,new Comparator<VersionDetail>(){
                @Override
                public int compare(VersionDetail o1, VersionDetail o2) {
                    String[] strs1=o1.getNamePrefix().split("\\.");
                    String[] strs2=o2.getNamePrefix().split("\\.");
                    int length=strs1.length>strs2.length?strs1.length:strs2.length;
                    for(int i=0;i<length;i++){
                        int num1=0;
                        int num2=0;
                        try{
                            num1=Integer.parseInt(strs1[i]);
                            num2=Integer.parseInt(strs2[i]);
                        }catch(Exception e){
                        }
                        if(num1<num2){
                            return -1;
                        }
                        if(num1>num2){
                            return 1;
                        }
                    }
                    return 0;
                }
            });*/
            arry = sortStr(arry);
            progressView.setVersionDetail(Arrays.asList(arry));
            return progressView;
        }
        return progressView;
    }

    public VersionDetail [] sortStr(VersionDetail [] str) {
        VersionDetail temp = null;
        for (int i = 0; i < str.length - 1; i++) {
            for (int j = i + 1; j < str.length; j++) {
                if (compareSize(str[i], str[j])) {
                    temp = str[i];
                    str[i] = str[j];
                    str[j] = temp;
                }
            }
        }
        return str;
    }

    private boolean compareSize(VersionDetail str1, VersionDetail str2) {
        // 注意点要用转译字符\\
        String[] s1 = str1.getNamePrefix().split("\\.");
        String[] s2 = str2.getNamePrefix().split("\\.");
        // 求出数组长度最短的大小
        int min = s1.length > s2.length ? s2.length : s1.length;
        int[] a1 = new int[min];
        int[] a2 = new int[min];
        // 把分开的字符串数组的每一个字符转成int类型
        for (int i = 0; i < min; i++) {
            a1[i] = Integer.parseInt(s1[i]);
            a2[i] = Integer.parseInt(s2[i]);
            if (a1[i] > a2[i]) {
                return true;
            } else if (a1[i] < a2[i]) {
                return false;
            }
        }
        // 前面部分都一样的时候，则判断字符串的长度，长度大说明该目录序列是大的
        if (s1.length > s2.length) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void removeProgressPojectVersion(ProgressViewCommand progressViewCommand) {
        LambdaQueryWrapper<VersionManageEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(progressViewCommand.getId()), VersionManageEntity::getId, progressViewCommand.getId());
        versionManageMapper.delete(lambdaQueryWrapper);
        LambdaQueryWrapper<VersionDetailEntity> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(progressViewCommand.getProjectId()), VersionDetailEntity::getProjectId, progressViewCommand.getProjectId());
        lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(progressViewCommand.getId()), VersionDetailEntity::getVersionManageId, progressViewCommand.getId());
        versionDetailMapper.delete(lambdaQueryWrapper1);
        /**
         * 删除任务
         */
        /*taskRemoteService.editTask(TaskRecordEditCommand.builder()
                .sourceFromId(progressViewCommand.getId())
                .taskType(TASK_TYPE)
                .taskName(TASK_NAME_PROGRESS_CONSTRUCTION_APPROVAL)
                .taskStatus("已完成")
                .oldStatus(new ArrayList<>(Collections.singletonList("进行中")))
                .finishTime(LocalDateTime.now())
                .build());*/
        taskRemoteService.deleteTask(progressViewCommand.getId(),TASK_TYPE);
    }

    @Override
    public ProgressDetail scheduleDetails(ProgressDetailCommand progressDetailCommand) {
        LambdaQueryWrapper<ProgressEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(progressDetailCommand.getProjectId()), ProgressEntity::getProjectId, progressDetailCommand.getProjectId());
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(progressDetailCommand.getId()), ProgressEntity::getId, progressDetailCommand.getId());
        ProgressEntity progressEntity = progressMapper.selectOne(lambdaQueryWrapper);
        ProgressDetail progressDetail = adapterConverter.progressEntityToProgressDetail(progressEntity);
        if (progressEntity != null){
            LambdaQueryWrapper<ProgressDetailEntity> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(progressDetailCommand.getProjectId()), ProgressDetailEntity::getProjectId, progressDetailCommand.getProjectId());
            lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(progressDetailCommand.getVersion()), ProgressDetailEntity::getVersion, progressDetailCommand.getVersion());
            lambdaQueryWrapper1.like(ObjectUtils.isNotNull(progressDetailCommand.getTaskType()), ProgressDetailEntity::getType, progressDetailCommand.getTaskType());
            lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(progressEntity.getId()), ProgressDetailEntity::getProjectScheduleId, progressEntity.getId());
            List<ProgressDetailEntity> progressDetailEntity = projectScheduleDetaillMapper.selectList(lambdaQueryWrapper1);
            List<ProjectScheduleDetail> lists = adapterConverter.progressDetailEntityToProjectScheduleDetail(progressDetailEntity);
            ProjectScheduleDetail[] arry = new ProjectScheduleDetail[lists.size()];
            for(int i = 0;i<lists.size();i++){
                arry[i] = lists.get(i);
            }
            arry = sortStr(arry);
            progressDetail.setProjectScheduleDetail(Arrays.asList(arry));
            return progressDetail;
        }
        return progressDetail;
    }

    public ProjectScheduleDetail [] sortStr(ProjectScheduleDetail [] str) {
        ProjectScheduleDetail temp = null;
        for (int i = 0; i < str.length - 1; i++) {
            for (int j = i + 1; j < str.length; j++) {
                if (compareSize(str[i], str[j])) {
                    temp = str[i];
                    str[i] = str[j];
                    str[j] = temp;
                }
            }
        }
        return str;
    }

    private boolean compareSize(ProjectScheduleDetail str1, ProjectScheduleDetail str2) {
        // 注意点要用转译字符\\
        String[] s1 = str1.getNamePrefix().split("\\.");
        String[] s2 = str2.getNamePrefix().split("\\.");
        // 求出数组长度最短的大小
        int min = s1.length > s2.length ? s2.length : s1.length;
        int[] a1 = new int[min];
        int[] a2 = new int[min];
        // 把分开的字符串数组的每一个字符转成int类型
        for (int i = 0; i < min; i++) {
            a1[i] = Integer.parseInt(s1[i]);
            a2[i] = Integer.parseInt(s2[i]);
            if (a1[i] > a2[i]) {
                return true;
            } else if (a1[i] < a2[i]) {
                return false;
            }
        }
        // 前面部分都一样的时候，则判断字符串的长度，长度大说明该目录序列是大的
        if (s1.length > s2.length) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public ProgressDetail keywordDetails(ProgressDetailCommand progressDetailCommand) {
        LambdaQueryWrapper<ProgressEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(progressDetailCommand.getProjectId()), ProgressEntity::getProjectId, progressDetailCommand.getProjectId());
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(progressDetailCommand.getId()), ProgressEntity::getId, progressDetailCommand.getId());
        ProgressEntity progressEntity = progressMapper.selectOne(lambdaQueryWrapper);
        ProgressDetail progressDetail = adapterConverter.progressEntityToProgressDetail(progressEntity);
        if (progressEntity != null){
            LambdaQueryWrapper<ProgressDetailEntity> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(progressDetailCommand.getProjectId()), ProgressDetailEntity::getProjectId, progressDetailCommand.getProjectId());
            lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(progressDetailCommand.getVersion()), ProgressDetailEntity::getVersion, progressDetailCommand.getVersion());
            lambdaQueryWrapper1.like(ObjectUtils.isNotNull(progressDetailCommand.getTaskType()), ProgressDetailEntity::getType, progressDetailCommand.getTaskType());
            lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(progressEntity.getId()), ProgressDetailEntity::getProjectScheduleId, progressEntity.getId());
            lambdaQueryWrapper1.orderByAsc(ProgressDetailEntity::getSortIndex);
            List<ProgressDetailEntity> progressDetailEntity = projectScheduleDetaillMapper.selectList(lambdaQueryWrapper1);
            List<ProjectScheduleDetail> lists = adapterConverter.progressDetailEntityToProjectScheduleDetail(progressDetailEntity);
            progressDetail.setProjectScheduleDetail(lists);
            return progressDetail;
        }
        return progressDetail;
    }

    @Override
    public ProgressKanbanDetails progressKanbanDDetails(ProgressDetailCommand progressDetailCommand) {
        LambdaQueryWrapper<ProgressEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(progressDetailCommand.getProjectId()), ProgressEntity::getProjectId, progressDetailCommand.getProjectId());
        lambdaQueryWrapper.eq(ObjectUtils.isNotNull(progressDetailCommand.getId()), ProgressEntity::getId, progressDetailCommand.getId());
        ProgressEntity progressEntity = progressMapper.selectOne(lambdaQueryWrapper);
        ProgressKanbanDetails progressKanbanDetails = adapterConverter.progressEntityToProgressKanbanDetails(progressEntity);
        if(progressEntity != null){
            LambdaQueryWrapper<ProgressDetailEntity> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(progressDetailCommand.getProjectId()), ProgressDetailEntity::getProjectId, progressDetailCommand.getProjectId());
            lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(progressEntity.getId()), ProgressDetailEntity::getProjectScheduleId, progressEntity.getId());
            lambdaQueryWrapper1.orderByAsc(ProgressDetailEntity::getSortIndex);
            List<ProgressDetailEntity> progressDetailEntity = projectScheduleDetaillMapper.selectList(lambdaQueryWrapper1);
            List<KanbanDetails> kanbanDetailsLists = adapterConverter.progressDetailEntityToKanbanDetails(progressDetailEntity);
            List<MilestoneNodeDetails> milestoneNodeDetailsLists = adapterConverter.progressDetailEntityToMilestoneNodeDetails(progressDetailEntity);
            progressKanbanDetails.setKanbanDetails(kanbanDetailsLists);
            progressKanbanDetails.setMilestoneNodeDetails(milestoneNodeDetailsLists);
            return progressKanbanDetails;
        }
        return progressKanbanDetails;
    }

    @Override
    public List<ProjectScheduleDetail> scheduleDetailsByAPP(ProgressDetailCommand progressDetailCommand) {
        LambdaQueryWrapper<VersionManageEntity> versionManageEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        versionManageEntityLambdaQueryWrapper.eq(VersionManageEntity ::getProjectId,progressDetailCommand.getProjectId());
        versionManageEntityLambdaQueryWrapper.eq(VersionManageEntity ::getMainCourtyardApproval,1);
        versionManageEntityLambdaQueryWrapper.orderByDesc(VersionManageEntity ::getVersion);
        List<VersionManageEntity> versionList = versionManageMapper.selectList(versionManageEntityLambdaQueryWrapper);
        List<ProjectScheduleDetail> lists = new ArrayList<>();
        if(versionList.size() > 0){
            //有待审批的版本信息，返回待审批的版本信息中，最大的版本号的数据
            VersionManageEntity versionManageEntity = versionList.get(0);

            LambdaQueryWrapper<VersionManageEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ObjectUtils.isNotNull(versionManageEntity.getProjectId()), VersionManageEntity::getProjectId, versionManageEntity.getProjectId());
            lambdaQueryWrapper.eq(ObjectUtils.isNotNull(versionManageEntity.getId()), VersionManageEntity::getId, versionManageEntity.getId());
            VersionManageEntity progressEntity = versionManageMapper.selectOne(lambdaQueryWrapper);
            if (progressEntity != null){
                LambdaQueryWrapper<VersionDetailEntity> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(progressDetailCommand.getProjectId()), VersionDetailEntity::getProjectId, progressDetailCommand.getProjectId());
                lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(progressEntity.getId()), VersionDetailEntity::getVersionManageId, progressEntity.getId());
                lambdaQueryWrapper1.like(ObjectUtils.isNotNull(progressDetailCommand.getTaskType()), VersionDetailEntity::getType, progressDetailCommand.getTaskType());
                List<VersionDetailEntity> versionDetails = versionDetailMapper.selectList(lambdaQueryWrapper1);
                List<VersionDetail> versioning = adapterConverter.versionDetailEntityToVersionDetail(versionDetails);
                for(VersionDetail v : versioning){
                    ProjectScheduleDetail projectScheduleDetail = new ProjectScheduleDetail();
                    projectScheduleDetail.setNamePrefix(v.getNamePrefix());
                    projectScheduleDetail.setName(v.getName());
                    projectScheduleDetail.setScheduleStartTime(v.getScheduleStartTime());
                    projectScheduleDetail.setScheduleEndTime(v.getScheduleEndTime());
                    projectScheduleDetail.setScheduleDuration(v.getSchduleDuration().intValue());
                    projectScheduleDetail.setRealStartTime(null);
                    projectScheduleDetail.setRealEndTime(null);
                    projectScheduleDetail.setPercentage(v.getPercentage());
                    projectScheduleDetail.setStatus(null);
                    projectScheduleDetail.setLagTime(null);
                    lists.add(projectScheduleDetail);
                }
            }
            return lists;

        }else{
            //无待审批的版本信息
            LambdaQueryWrapper<ProgressEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ObjectUtils.isNotNull(progressDetailCommand.getProjectId()), ProgressEntity::getProjectId, progressDetailCommand.getProjectId());
            lambdaQueryWrapper.eq(ObjectUtils.isNotNull(progressDetailCommand.getId()), ProgressEntity::getId, progressDetailCommand.getId());
            ProgressEntity progressEntity = progressMapper.selectOne(lambdaQueryWrapper);
            ProgressDetail progressDetail = adapterConverter.progressEntityToProgressDetail(progressEntity);
            if (progressEntity != null){
                LambdaQueryWrapper<ProgressDetailEntity> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(progressDetailCommand.getProjectId()), ProgressDetailEntity::getProjectId, progressDetailCommand.getProjectId());
                lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(progressDetailCommand.getVersion()), ProgressDetailEntity::getVersion, progressDetailCommand.getVersion());
                lambdaQueryWrapper1.like(ObjectUtils.isNotNull(progressDetailCommand.getTaskType()), ProgressDetailEntity::getType, progressDetailCommand.getTaskType());
                lambdaQueryWrapper1.eq(ObjectUtils.isNotNull(progressEntity.getId()), ProgressDetailEntity::getProjectScheduleId, progressEntity.getId());
                lambdaQueryWrapper1.orderByAsc(ProgressDetailEntity::getSortIndex);
                List<ProgressDetailEntity> progressDetailEntity = projectScheduleDetaillMapper.selectList(lambdaQueryWrapper1);
                lists = adapterConverter.progressDetailEntityToProjectScheduleDetail(progressDetailEntity);
            }
            return lists;
        }

    }
}
